//
//  HEIMInputView.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/12/2.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEIMInputView.h"
#import "HEItemBtnView.h"
#import "YTRecordStatusView.h"
#import "HEAudioRecordManage.h"
#import "HEIMAudioObject.h"
#import "HXPhotoPicker.h"
#import "HEIMImageObject.h"
#import "HEConsulRecoderListViewController.h"
#import "HEIMVideoObject.h"
#import "HEATPersonListViewController.h"
#import "YYTextAttachmentManager.h"
#import "NSAttributedString+YY.h"
#import "HEIMATObject.h"

@interface HEIMInputView ()<QMUITextViewDelegate, HEAudioRecordManageDelegate>

@property(nonatomic, strong) QMUITextView *textView;
@property(nonatomic, strong) UIView *self;
@property(nonatomic, strong) UIView *tabbarWarp;
@property(nonatomic, strong) UIView *addView;
@property(nonatomic, strong) UIButton *yuyinView;
@property(nonatomic, strong) UIButton *addBtn;

@property(nonatomic, assign) BOOL fristInto;
@property(nonatomic, assign) CGFloat transformY;

@property(nonatomic, assign) CGFloat panelheight;
@property(nonatomic, assign) CGFloat currentPanelOffest;
@property(nonatomic, strong) UIView *currentPanelView;
@property(nonatomic, assign) CGFloat currentTextWarpHeight;

@property(nonatomic, strong) UIButton *audioBtn;
@property(nonatomic,strong) YTRecordStatusView *recordStatusView;

@property(nonatomic,strong) UserInfo *userInfo;

@property(nonatomic,strong) HXPhotoManager *photoManage;

@property(nonatomic,strong) HXPhotoManager *videoManage;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;
@property(nonatomic, assign) BOOL isHidden;

@property (nonatomic, assign) BOOL needBack;

@end

@implementation HEIMInputView

- (instancetype)initWithFrame:(CGRect)frame type:(HEIMUserModelType)type {

    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = KWhiteColor;
        
        self.qmui_borderPosition = QMUIViewBorderPositionTop;
        self.qmui_borderWidth = 1;
        self.qmui_borderColor = CSplitLineColor;

        _type = type;
        _currentTextWarpHeight = 49;

        [self initUI];
        self.recordStatusView = [YTRecordStatusView Instance];

        _userInfo = [[UserManager sharedUserManager] getUserInfo];


        [HEAudioRecordManage sharedManager].delegate = self;

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotify:) name:UIKeyboardWillChangeFrameNotification object:nil];

    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = KWhiteColor;
        
        _type = HEIMUserModelTypeIM;
        self.qmui_borderPosition = QMUIViewBorderPositionTop;
        self.qmui_borderWidth = 1;
        self.qmui_borderColor = CSplitLineColor;

        _currentTextWarpHeight = 49;

        [self initUI];
        self.recordStatusView = [YTRecordStatusView Instance];

        _userInfo = [[UserManager sharedUserManager] getUserInfo];


        [HEAudioRecordManage sharedManager].delegate = self;

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotify:) name:UIKeyboardWillChangeFrameNotification object:nil];

    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)initUI {
    UIView *tabbarWarp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 49)];
    _tabbarWarp = tabbarWarp;
    tabbarWarp.qmui_borderPosition = QMUIViewBorderPositionBottom;
    tabbarWarp.qmui_borderWidth = 1;
    tabbarWarp.qmui_borderColor = CSplitLineColor;
    [self addSubview:tabbarWarp];
    
    
    // 语音
    UIButton *yuyinView = [UIButton buttonWithType:UIButtonTypeCustom];
    [yuyinView setImage:IMAGE_NAMED(@"voice") forState:UIControlStateNormal];
    [tabbarWarp addSubview:yuyinView];
    [yuyinView addTarget:self action:@selector(voiceClick:) forControlEvents:UIControlEventTouchUpInside]; 
    _yuyinView = yuyinView;
    [yuyinView setImage:IMAGE_NAMED(@"voice") forState:UIControlStateDisabled];
    [yuyinView setImage:IMAGE_NAMED(@"print") forState:UIControlStateSelected];
    
    
    // 语音输入
    UIButton *audioBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    audioBtn.titleLabel.font = DYBlodFont(15);
    [audioBtn setTitleColor: CNavLightBlackColor forState:UIControlStateNormal];
    [audioBtn setTitle:@"按住 说话" forState:UIControlStateNormal];
    [tabbarWarp addSubview:audioBtn];
    _audioBtn = audioBtn;
    audioBtn.hidden = YES;
    audioBtn.layer.borderWidth = 1;
    audioBtn.layer.borderColor = CNavSubTitleColor.CGColor;
    audioBtn.layer.cornerRadius = 5;
    [audioBtn addTarget:self action:@selector(startRecordVoice) forControlEvents:UIControlEventTouchDown];
    [audioBtn addTarget:self action:@selector(confirmRecordVoice) forControlEvents:UIControlEventTouchUpInside];
    [audioBtn addTarget:self action:@selector(cancelRecordVoice) forControlEvents:UIControlEventTouchUpOutside];
    [audioBtn addTarget:self action:@selector(updateContinueRecordVoice) forControlEvents:UIControlEventTouchDragEnter];
    [audioBtn addTarget:self action:@selector(updateCancelRecordVoice) forControlEvents:UIControlEventTouchDragExit];

    // 输入框
    _textView = [[QMUITextView  alloc] initWithFrame:CGRectMake(35, 6, 200, 49 - 6 * 2)];
    _textView.placeholder = @"请输入内容";
    _textView.maximumTextLength = 15000;
    _textView.maximumHeight = 150;
    _textView.placeholderColor = CNavSubTitleColor; // 自定义 placeholder 的颜色
    _textView.placeholderMargins = UIEdgeInsetsMake(0, 7, 0, 7);
    _textView.typingAttributes = @{NSFontAttributeName: UIFontMake(16),
                                       NSParagraphStyleAttributeName: [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:20]
    };
    _textView.backgroundColor = CSplitLineColor;
    _textView.layer.cornerRadius = 4;
    _textView.returnKeyType = UIReturnKeySend;
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    NSDictionary *attributes = @{NSParagraphStyleAttributeName:paragraphStyle};
    _textView.attributedText = [[NSAttributedString alloc]initWithString:_textView.text attributes:attributes];

    [_textView setDelegate:self];
    [tabbarWarp addSubview:_textView];
    
    UIView *nomralView = [UIView new];
    [self addSubview:nomralView]; 
    
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setImage:IMAGE_NAMED(@"add_media") forState:UIControlStateNormal];
    [addBtn setTitleColor:KWhiteColor forState:UIControlStateNormal];
    addBtn.titleLabel.font = DYBlodFont(15);
    [nomralView addSubview:addBtn];
    [addBtn addTarget:self action:@selector(addBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _addBtn = addBtn;
    
 
    [yuyinView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(tabbarWarp);
        make.left.equalTo(tabbarWarp).offset(10);
        make.width.equalTo(@27);
        make.height.equalTo(@27);
    }];
     
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tabbarWarp).mas_offset(6);
        make.left.equalTo(yuyinView.mas_right).offset(10);
        make.right.equalTo(nomralView.mas_left).offset(-10);
        make.bottom.equalTo(tabbarWarp).mas_offset(-6);
    }];
    
    [audioBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tabbarWarp).mas_offset(6);
        make.left.equalTo(yuyinView.mas_right).offset(10);
        make.right.equalTo(nomralView.mas_left).offset(-10);
        make.height.mas_offset(49 - 6*2);
    }];
    
    [nomralView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(tabbarWarp);
        make.right.equalTo(tabbarWarp).offset(-10);
        make.width.mas_offset(32 * 1 + 10);
    }];
    
    [addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nomralView).offset(5);
        make.left.right.equalTo(nomralView);
        make.bottom.equalTo(nomralView).offset(-5);
    }];
    
//    NSArray *arr1 = @[addView];
//    [arr1 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(nomralView).offset(5);
//        make.bottom.equalTo(nomralView).offset(-5);
//    }];
//    [arr1 mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:10 leadSpacing:0 tailSpacing:0];
    
}

/**
 *  当键盘改变了frame(位置和尺寸)的时候调用
 */
- (void)keyboardWillChangeFrameNotify:(NSNotification*)notify {
    CGFloat tabbarHeight = self.height;
    
    if (self.isHidden) {
        tabbarHeight = 0;
    }
    
    _fristInto = NO;
    
    // 0.取出键盘动画的时间
    CGFloat duration = [notify.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 1.取得键盘最后的frame
    CGRect keyboardFrame = [notify.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat keyBordOriginY = keyboardFrame.origin.y;
    BOOL iOS7 = ([[[UIDevice currentDevice] systemVersion] doubleValue] < 8.0);
    UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];
    if (iOS7 && (orientation == UIDeviceOrientationLandscapeLeft
                 || orientation == UIDeviceOrientationLandscapeRight)) {
        keyBordOriginY = keyboardFrame.origin.x + keyboardFrame.size.width;
    }
 
    // 2.计算控制器的view需要平移的距离
    CGFloat transformY = keyBordOriginY - kScreenHeight;
    _transformY = transformY;
    
    // 3.执行动画
    [UIView animateWithDuration:duration animations:^{
        self.tableView.frame = CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight - tabbarHeight + transformY );
        self.transform = CGAffineTransformMakeTranslation(0, transformY);
        [self scrollToBottom];
    }];
}

- (void)addBtnClick:(UIButton *)sender {
    [self addSubview:self.addView];
    BOOL isShow = !sender.selected;
    
    if (isShow) {
        _yuyinView.selected = NO;
        _textView.hidden = NO;
        _audioBtn.hidden = YES;
//        [_textView becomeFirstResponder];
    }
   
    CGFloat offest = isShow ? self.addView.height : 0;
    _currentPanelOffest = offest;
    _currentPanelView = self.addView;
    
    [self changeInputWithPanel:self.addView panelOffest:offest animations:^{
        
    } completion:^(BOOL finished) {
        if (!isShow) {
            [self.addView removeFromSuperview];
        }
    }];
    
    sender.selected = !sender.selected;

}

- (void)changeInputWithPanel:(UIView *)view panelOffest:(CGFloat)panelOffest animations:(void (^)(void))animations completion:(void (^ __nullable)(BOOL finished))completion{
    
    // 文字高度
    CGFloat textWarpHeight = _tabbarWarp.height;
    
    [self updatePanelViewTop];
     
    CGFloat tabbarHeight = _tabbarWarp.height + KSafeTabbarHeight;

    // 3.执行动画
    KWeakSelf
    [UIView animateWithDuration:.3 animations:^{
        animations();
        self.frame = CGRectMake(self.zx_x, kScreenHeight + weakSelf.transformY - textWarpHeight - panelOffest, self.zx_width, textWarpHeight + panelOffest);

        self.tableView.frame = CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight - tabbarHeight + weakSelf.transformY - panelOffest);
        [self scrollToBottom];
    } completion:^(BOOL finished) {
        completion(finished);
    }];
}

- (void)showAddPanel {
    
}

#pragma mark -

/**
 *  开始录音
 */
- (void)startRecordVoice {
    [_recordStatusView dismiss];
    [_recordStatusView showInWindow];
    
    [[HEAudioRecordManage sharedManager] startRecord];
    
    [[HEAudioRecordManage sharedManager] updatePower:^(CGFloat power) {
        [self.recordStatusView updateWithPower:power];
    }];
}

/**
 *  更新录音显示状态,手指向上滑动后 提示松开取消录音
 */
- (void)updateCancelRecordVoice {
    _recordStatusView.voiceActionMode = VoiceMode_ReleaseToCancel;
}

/**
 *  取消录音
 */
- (void)cancelRecordVoice { 
    _recordStatusView.voiceActionMode = VoiceMode_ReleaseToCancel;
    [_recordStatusView dismiss];
    
    [[HEAudioRecordManage sharedManager] cancelRecord];
}

/**
 *  更新录音状态, 手指重新滑动到范围内,提示向上取消录音
 */
- (void)updateContinueRecordVoice {
    _recordStatusView.voiceActionMode = VoiceMode_ReleaseToSend;
}

/**
 *  录音结束
 */
- (void)confirmRecordVoice {
    [_recordStatusView dismiss];
    [[HEAudioRecordManage sharedManager] endRecord];
}

/**
 *  录音时间短
 */
- (void)showShotTimeSign {
    [_recordStatusView dismiss];
    [[HEAudioRecordManage sharedManager] cancelRecord];
}

- (void)voiceClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    CGFloat textWarpH = 0;
 
    if (sender.selected) {
        _audioBtn.hidden = NO;
        _textView.hidden = YES;
        
        textWarpH = 49;
        
        [_textView resignFirstResponder];
        [self changeInputWithPanel:self.addView panelOffest:0 animations:^{
        } completion:^(BOOL finished) {
            self.addBtn.selected = NO;
            [self.addView removeFromSuperview];
        }];
    }else {
        _textView.hidden = NO;
        _audioBtn.hidden = YES;
        
        textWarpH = _currentTextWarpHeight;
        
//        [_textView becomeFirstResponder];
//        _tabbarWarp.frame = CGRectMake(_tabbarWarp.zx_x, _tabbarWarp.zx_y, _tabbarWarp.zx_width, textWarpH);
//        self.frame = CGRectMake(self.zx_x, kScreenHeight + _transformY - textWarpH - _currentPanelOffest, self.zx_width, textWarpH + _currentPanelOffest);
//        self.tableView.frame = CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight - self.height - KSafeTabbarHeight + _transformY );
//        [self updatePanelViewTop];
    }
}

- (void)scrollToBottom {
    [self.tableView layoutIfNeeded];
    CGFloat yOffset = 0; //设置要滚动的位置 0最顶部 CGFLOAT_MAX最底部
    if (self.tableView.contentSize.height > self.tableView.bounds.size.height) {
        yOffset = self.tableView.contentSize.height - self.tableView.bounds.size.height;
    }
    [self.tableView setContentOffset:CGPointMake(0, yOffset) animated: !self.fristInto];
}

- (void)updatePanelViewTop {
    // 更新面板的顶部y距离，防止遮挡输入多行文字
    CGRect vf = _currentPanelView.frame;
    vf.origin.y = _tabbarWarp.height;
    _currentPanelView.frame = vf;
}

#pragma mark - HEAudioRecordManageDelegate
- (void)audioRecordFinishedWithFilePath:(NSString *)filePath time:(NSInteger)time {
    if (time < 1) {
        [Dialog toastBottom:@"说话时间太短!"];
        return;
    }
    
    if ([_delegate respondsToSelector:@selector(sendMessage:)]) {
        
        HEIMAudioObject *audio = [HEIMAudioObject new];
        audio.url = filePath;
        audio.duration = time;
         
        HEIMMessage *textMessage = [[HEIMMessage alloc] init];
        textMessage.modelType = _type;
        textMessage.type = HEIMMessageTypeAudio;
        textMessage.from = _userInfo.id;
        textMessage.to =  [HEIMKit sharedKit].receiveInfo.infoId;
        textMessage.actor = HEActorTypeUser;
        textMessage.messageObject = audio;
        
        HEIMMessageModel *model = [[HEIMMessageModel alloc] initWithMessage:textMessage];
        model.deliveryState = HEIMMessageDeliveryStateDelivering;
         
        [_delegate sendMessage: model];
    }
}

#pragma mark - <QMUITextViewDelegate>
// 实现这个 delegate 方法就可以实现自增高
- (void)textView:(QMUITextView *)textView newHeightAfterTextChanged:(CGFloat)height {
 
    CGFloat he = height + 6 *2;
      
    if (he > self.height) {
        _tabbarWarp.frame = CGRectMake(_tabbarWarp.zx_x, _tabbarWarp.zx_y, _tabbarWarp.zx_width, he);
        self.frame = CGRectMake(self.zx_x, kScreenHeight + _transformY - he - _currentPanelOffest, self.zx_width, he + _currentPanelOffest);

//        self.frame = CGRectMake(self.zx_x, self.zx_y - offest, self.zx_width, self.height + offest + _currentPanelOffest);
    }else {
        if (he > 49) {
            _tabbarWarp.frame = CGRectMake(_tabbarWarp.zx_x, _tabbarWarp.zx_y, _tabbarWarp.zx_width, he);
            self.frame = CGRectMake(self.zx_x, kScreenHeight + _transformY - he - _currentPanelOffest, self.zx_width, he + _currentPanelOffest);

        }else {
            CGFloat height = _yuyinView.isSelected ? (_panelheight + 49) : 49;
            _tabbarWarp.frame = CGRectMake(_tabbarWarp.zx_x, _tabbarWarp.zx_y, _tabbarWarp.zx_width, 49);
//            self.frame = CGRectMake(self.zx_x, kScreenHeight + _transformY - height - _currentPanelOffest, self.zx_width, height + _currentPanelOffest);
            self.frame = CGRectMake(self.zx_x, kScreenHeight + _transformY - height - _currentPanelOffest, self.zx_width, height + _currentPanelOffest);

        }
    }
    _currentTextWarpHeight = _tabbarWarp.height;
    [self updatePanelViewTop];
    self.tableView.frame = CGRectMake(0, ZXNavBarHeight, KScreenWidth, self.top - ZXNavBarHeight);
}
 
- (void)textView:(QMUITextView *)textView didPreventTextChangeInRange:(NSRange)range replacementText:(NSString *)replacementText {
    [Dialog toast:[NSString stringWithFormat:@"文字不能超过%@个字符", @(textView.maximumTextLength)] delay:2.0];
}

- (BOOL)textViewShouldReturn:(QMUITextView *)textView {

    NSString *text = textView.text.qmui_trim;
    if ([DYTools isBlankString:text]) {
        [Dialog toastBottom:@"不能发送空白消息!"];
        return YES;
    }
    
    if ([_delegate respondsToSelector:@selector(sendMessage:)]) {
        
        NSDictionary *attcahInfo = [_textView.attributedText getAttachInfo];
        NSArray *ids = attcahInfo[@"ids"];
        
        if (ids.count > 0) {
            
            HEIMATObject *atObject = [HEIMATObject new];
            atObject.atIds = ids;
            
            HEIMMessage *textMessage = [[HEIMMessage alloc] init];
            textMessage.modelType = _type;
            textMessage.type = HEIMMessageTypeAT;
            textMessage.text = attcahInfo[@"text"];
            textMessage.from = _userInfo.id;
            textMessage.to = [HEIMKit sharedKit].receiveInfo.infoId;
            textMessage.actor = HEActorTypeUser;
            textMessage.messageObject = atObject;
            
            HEIMMessageModel *model = [[HEIMMessageModel alloc] initWithMessage:textMessage];
            model.deliveryState = HEIMMessageDeliveryStateDelivering;
            
            [_delegate sendMessage: model];
            textView.attributedText = nil;

        }else {
            
            HEIMMessage *textMessage = [[HEIMMessage alloc] init];
            textMessage.modelType = _type;
            textMessage.type = HEIMMessageTypeText;
            textMessage.text = text;
            textMessage.from = _userInfo.id;
            textMessage.to =  [HEIMKit sharedKit].receiveInfo.infoId;
            textMessage.actor = HEActorTypeUser;
            HEIMMessageModel *model = [[HEIMMessageModel alloc] initWithMessage:textMessage];
            model.deliveryState = HEIMMessageDeliveryStateDelivering;
             
            [_delegate sendMessage: model];
        }
        
        textView.text = nil;
    }
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(nonnull NSString *)text {
    // Insert @ and mention.
    if ([text isEqualToString:@"@"]) {
        
        if (range.length > 0) {
            NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:text];
//            [self.textView.textStorage replaceCharactersInRange:range withAttributedString:attributedString];
        }
        
        self.needBack = YES; //需要将手动输入的@删除
        
        KWeakSelf
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf presentPersonListViewController];
        });
        return YES;
    }
    
    // 解决点击发送按钮换行问题
    if ([text isEqualToString:@"\n"]) {
         [textView resignFirstResponder];
         return NO;
     }
    
    return YES;
}

- (void)textViewDidChangeSelection:(UITextView *)textView {
    DLog(@"")
}

- (void)presentPersonListViewController {
    UIViewController *superVC = (UIViewController *)self.delegate;
    
    HEATPersonListViewController *vc = [HEATPersonListViewController new];
    vc.dataSource = self.teamUserList;
    
    KWeakSelf
    [vc vcBackParamBlock:^(HEIMKitInfo *info) {
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
        NSDictionary *attributes = @{NSFontAttributeName:self.textView.font, NSParagraphStyleAttributeName:paragraphStyle};
//        NSMutableArray *currentSelectedPersonItems = [[self.textView.attributedText getCurrentAtPersonItems] mutableCopy];
//        [currentSelectedPersonItems addObject:info];//这里可以判断去重...（根据自己需求情况而定）

        //将人的名字转化为NSTextAttachment
        [[YYTextAttachmentManager getInstance] transformTextWithTextView:self.textView tickedPersonItems:@[info] atAllPersons:nil canRepeat:YES needBack:self.needBack isLong:NO color:CNavBgColor attributes:attributes completeBlock:^(NSMutableAttributedString *mutableAttributedString, NSRange selectedRange) {
            weakSelf.needBack = NO;
            weakSelf.textView.attributedText = mutableAttributedString;
            weakSelf.textView.selectedRange = selectedRange;
        }];
    }];
    HEBaseNavigationController *nav= [[HEBaseNavigationController alloc] initWithRootViewController:vc];
    [superVC presentViewController:nav animated:YES completion:nil];
}

- (void)addATPerson:(HEIMKitInfo *)info {
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    NSDictionary *attributes = @{NSFontAttributeName:self.textView.font, NSParagraphStyleAttributeName:paragraphStyle};

    //将人的名字转化为NSTextAttachment
    KWeakSelf
    [[YYTextAttachmentManager getInstance] transformTextWithTextView:self.textView tickedPersonItems:@[info] atAllPersons:nil canRepeat:YES needBack:self.needBack isLong:NO color:CNavBgColor attributes:attributes completeBlock:^(NSMutableAttributedString *mutableAttributedString, NSRange selectedRange) {
        weakSelf.needBack = NO;
        weakSelf.textView.selectedRange = selectedRange;
        weakSelf.textView.attributedText = mutableAttributedString;
    }];
}

#pragma mark -
- (UIView *)addView {
    if (!_addView) {
        _addView = [[UIView alloc] initWithFrame:CGRectMake(0, _tabbarWarp.height, KScreenWidth, 100)];
//        _addView.backgroundColor = UIColor.orangeColor;
        
//        QMUIButton *photoBtn = [[QMUIButton alloc] init];
//        photoBtn.imagePosition = QMUIButtonImagePositionTop;// 将图片位置改为在文字下方
//        photoBtn.tintColorAdjustsTitleAndImage = CNavSubTitleColor;
//        photoBtn.adjustsImageTintColorAutomatically = NO;
//        photoBtn.spacingBetweenImageAndTitle = 15;
//        [photoBtn setImage:UIImageMake(@"open_img_picker") forState:UIControlStateNormal];
//        [photoBtn setTitle:@"图片" forState:UIControlStateNormal];
//        photoBtn.titleLabel.font = DYFont(15);
//        [_addView addSubview: photoBtn];
//        [photoBtn addTarget:self action:@selector(selectPhotoClick) forControlEvents:UIControlEventTouchUpInside];
//
//        QMUIButton *consulReportBtn = [[QMUIButton alloc] init];
//        consulReportBtn.imagePosition = QMUIButtonImagePositionTop;// 将图片位置改为在文字下方
//        consulReportBtn.tintColorAdjustsTitleAndImage = CNavSubTitleColor;
//        consulReportBtn.adjustsImageTintColorAutomatically = NO;
//        consulReportBtn.spacingBetweenImageAndTitle = 15;
//        [consulReportBtn setImage:UIImageMake(@"add_report") forState:UIControlStateNormal];
//        [consulReportBtn setTitle:@"咨询报告" forState:UIControlStateNormal];
//        consulReportBtn.titleLabel.font = DYFont(15);
//        [_addView addSubview: consulReportBtn];
//        [consulReportBtn addTarget:self action:@selector(selectConsulReportClick) forControlEvents:UIControlEventTouchUpInside];
        
        HEItemBtnView *photoBtn = [HEItemBtnView new];
        photoBtn.title = @"图片";
        photoBtn.imageName = @"open_img_picker";
        [_addView addSubview: photoBtn];
        
        [photoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_addView).offset(15);
            make.left.equalTo(_addView).offset(15);
            make.width.offset([photoBtn.title widthForFont:DYFont(15)] + 10);
            make.height.offset(50); 
        }];
        
        photoBtn.selectBlock = ^(HEItemBtnView * _Nonnull btn) {
            [self selectPhotoClick];
        };
        
        if (_type == HEIMUserModelTypeIM ||
            _type == HEIMUserModelTypeTeamIM) {
            HEItemBtnView *consulReportBtn = [HEItemBtnView new];
            consulReportBtn.title = @"咨询报告";
            consulReportBtn.imageName = @"add_report";
            [_addView addSubview: consulReportBtn];
            
            [consulReportBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_addView).offset(15);
                make.left.equalTo(photoBtn.mas_right).offset(20);
                make.width.offset([consulReportBtn.title widthForFont:DYFont(15)] + 5);
                make.height.offset(50);
            }];
            
            consulReportBtn.selectBlock = ^(HEItemBtnView * _Nonnull btn) {
                [self selectConsulReportClick];
            };
        }else {
            HEItemBtnView *videoBtn = [HEItemBtnView new];
            videoBtn.title = @"视频";
            videoBtn.imageName = @"inp_video";
            [_addView addSubview: videoBtn];
            
            [videoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_addView).offset(15);
                make.left.equalTo(photoBtn.mas_right).offset(20);
                make.width.offset([videoBtn.title widthForFont:DYFont(15)] + 5);
                make.height.offset(50);
            }];
            
            videoBtn.selectBlock = ^(HEItemBtnView * _Nonnull btn) {
                [self selectVideoClick];
            };
        }
          
        
//        NSArray *arr = @[photoBtn, consulReportBtn];
//        [arr mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(_addView).offset(5);
//            make.bottom.equalTo(_addView).offset(-15);
//        }];
//        [arr mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(_addView).offset(5);
//            make.bottom.equalTo(_addView).offset(-15);
//        }];
//
//        [arr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:10 leadSpacing:0 tailSpacing:0];
        
    }
    return _addView;
}

- (void)selectPhotoClick {
    
    HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithManager:self.photoManage doneBlock:^(NSArray<HXPhotoModel *> * _Nullable allList, NSArray<HXPhotoModel *> * _Nullable photoList, NSArray<HXPhotoModel *> * _Nullable videoList, BOOL original, UIViewController * _Nullable viewController, HXPhotoManager * _Nullable manager) {
        
        NSMutableArray *arr = @[].mutableCopy;
        
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            self.group = dispatch_group_create();
            
            for (HXPhotoModel *item in photoList) {
                dispatch_group_enter(self.group);

                [item getAssetURLWithSuccess:^(NSURL * _Nullable URL, HXPhotoModelMediaSubType mediaType, BOOL isNetwork, HXPhotoModel * _Nullable model) {
                    HEIMImageObject *image = [[HEIMImageObject alloc] init];
                    image.url = URL;
                    image.imageSourceType = HEIMImageSourceTypeNative;
                    [arr addObject: image];
                    dispatch_group_leave(self.group);

                } failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
                    dispatch_group_leave(self.group);
                }];
            }
            
            //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
            KWeakSelf
            dispatch_group_notify(self.group, queue, ^{
                
                if ([self.delegate respondsToSelector:@selector(sendMessage:)]) {
                    HEIMImageObject *image = [[HEIMImageObject alloc] init];
                    image.imageArray = arr;
                    
                    HEIMMessage *message = [[HEIMMessage alloc] init];
                    message.modelType = weakSelf.type;
                    message.type = HEIMMessageTypeImage;
                    message.messageObject = image;
                    message.from = self.userInfo.id;
                    message.actor = HEActorTypeUser;
                    message.to = [HEIMKit sharedKit].receiveInfo.infoId;
                    HEIMMessageModel *model = [[HEIMMessageModel alloc] initWithMessage: message];
                    model.deliveryState = HEIMMessageDeliveryStateDelivering;
         
                    [self.delegate sendMessage: model];
                }
            });
        });
    } cancelBlock:^(UIViewController * _Nullable viewController, HXPhotoManager * _Nullable manager) {
        
    }];
    
    UIViewController *vc = (UIViewController *)self.delegate;
    [vc presentViewController:nav animated:YES completion:nil];
}

- (void)selectConsulReportClick {
    __weak typeof(self) weakself = self;

    HEConsulRecoderListViewController *vc = [HEConsulRecoderListViewController new];
    vc.intoType = HEConsulReportVCIntoTypeFromIM;
    UIViewController *superVC = (UIViewController *)self.delegate;
    [superVC.navigationController pushViewController:vc animated:YES];
    
    vc.backBlock = ^(HECosulReportModel * _Nonnull model) {
        if ([weakself.delegate respondsToSelector:@selector(sendMessage:)]) {
            HEIMMessage *message = [[HEIMMessage alloc] init];
            message.modelType = weakself.type;
            message.type = HEIMMessageTypeConsulReport;
            message.title = model.report_name;
            message.text = model.inst_id;
            message.from = weakself.userInfo.id;
            message.to =  [HEIMKit sharedKit].receiveInfo.infoId;
            message.actor = HEActorTypeUser;
            HEIMMessageModel *model = [[HEIMMessageModel alloc] initWithMessage: message];
            model.deliveryState = HEIMMessageDeliveryStateDelivering; 
            [weakself.delegate sendMessage: model];
        }
    };
}

- (void)selectVideoClick {
    
    HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithManager:self.videoManage doneBlock:^(NSArray<HXPhotoModel *> * _Nullable allList, NSArray<HXPhotoModel *> * _Nullable photoList, NSArray<HXPhotoModel *> * _Nullable videoList, BOOL original, UIViewController * _Nullable viewController, HXPhotoManager * _Nullable manager) {
        
        NSMutableArray *arr = @[].mutableCopy;

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            self.group = dispatch_group_create();

            for (HXPhotoModel *item in videoList) {
                dispatch_group_enter(self.group);

                [item getAssetURLWithSuccess:^(NSURL * _Nullable URL, HXPhotoModelMediaSubType mediaType, BOOL isNetwork, HXPhotoModel * _Nullable model) {
                    HEIMVideoObject *video = [[HEIMVideoObject alloc] init];
                    video.url = URL;
                    video.sourceType = HEIMMediaSourceTypeNative;
                    [arr addObject: video];
                    dispatch_group_leave(self.group);

                } failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
                    dispatch_group_leave(self.group);
                }];
            }

            //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
            dispatch_group_notify(self.group, queue, ^{
                
                for (HEIMVideoObject *video in arr) {
                    HEIMMessage *message = [[HEIMMessage alloc] init];
                    message.type = HEIMMessageTypeVideo;
                    message.messageObject = video;
                    message.from = self.userInfo.id;
                    message.actor = HEActorTypeUser;
                    message.to = [HEIMKit sharedKit].receiveInfo.infoId;
                    HEIMMessageModel *model = [[HEIMMessageModel alloc] initWithMessage: message];
                    model.deliveryState = HEIMMessageDeliveryStateDelivering;

                    if ([self.delegate respondsToSelector:@selector(sendMessage:)]) {
                        [self.delegate sendMessage: model];
                    }
                }
            });
        });
    } cancelBlock:^(UIViewController * _Nullable viewController, HXPhotoManager * _Nullable manager) {
        
    }];
    
    UIViewController *vc = (UIViewController *)self.delegate;
    [vc presentViewController:nav animated:YES completion:nil];
}


/**
 前往相机
 */
- (void)goCameraViewController {
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [[self hx_viewController].view hx_showImageHUDText:[NSBundle hx_localizedStringForKey:@"无法使用相机!"]];
        return;
    }
    HXWeakSelf
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                if (weakSelf.videoManage.configuration.replaceCameraViewController) {
                    HXPhotoConfigurationCameraType cameraType;
                    if (weakSelf.videoManage.type == HXPhotoManagerSelectedTypePhoto) {
                        cameraType = HXPhotoConfigurationCameraTypePhoto;
                    }else if (weakSelf.videoManage.type == HXPhotoManagerSelectedTypeVideo) {
                        cameraType = HXPhotoConfigurationCameraTypeVideo;
                    }else {
                        if (!weakSelf.videoManage.configuration.selectTogether) {
                            if (weakSelf.videoManage.afterSelectedPhotoArray.count > 0) {
                                cameraType = HXPhotoConfigurationCameraTypePhoto;
                            }else if (weakSelf.videoManage.afterSelectedVideoArray.count > 0) {
                                cameraType = HXPhotoConfigurationCameraTypeVideo;
                            }else {
                                cameraType = HXPhotoConfigurationCameraTypePhotoAndVideo;
                            }
                        }else {
                            cameraType = HXPhotoConfigurationCameraTypePhotoAndVideo;
                        }
                    }
                    switch (weakSelf.videoManage.configuration.customCameraType) {
                        case HXPhotoCustomCameraTypePhoto:
                            cameraType = HXPhotoConfigurationCameraTypePhoto;
                            break;
                        case HXPhotoCustomCameraTypeVideo:
                            cameraType = HXPhotoConfigurationCameraTypeVideo;
                            break;
                        case HXPhotoCustomCameraTypePhotoAndVideo:
                            cameraType = HXPhotoConfigurationCameraTypePhotoAndVideo;
                            break;
                        default:
                            break;
                    }
                    if (weakSelf.videoManage.configuration.shouldUseCamera) {
                        weakSelf.videoManage.configuration.shouldUseCamera([weakSelf hx_viewController], cameraType, weakSelf.videoManage);
                    }
                    weakSelf.videoManage.configuration.useCameraComplete = ^(HXPhotoModel *model) {
                        [weakSelf customCameraViewController:nil didDone:model];
                    };
                    return;
                }
                HXCustomCameraViewController *vc = [[HXCustomCameraViewController alloc] init];
                vc.delegate = weakSelf;
                vc.manager = weakSelf.videoManage;
                vc.isOutside = YES;
                HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithRootViewController:vc];
                nav.isCamera = YES;
                nav.supportRotation = weakSelf.videoManage.configuration.supportRotation;
                nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
                nav.modalPresentationCapturesStatusBarAppearance = YES;
                [[weakSelf hx_viewController] presentViewController:nav animated:YES completion:nil];
            }else {
                [HXPhotoTools showUnusableCameraAlert:weakSelf.hx_viewController];
            }
        });
    }];
}

- (void)customCameraViewController:(HXCustomCameraViewController *)viewController didDone:(HXPhotoModel *)model {
    [self cameraDidNextClick:model];
}
/**
 相机拍完之后的代理

 @param model 照片模型
 */
- (void)cameraDidNextClick:(HXPhotoModel *)model {
    
}

- (void)hideView {
    [_textView resignFirstResponder];
    self.hidden = YES;
    _isHidden = YES;
    self.tableView.frame = CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight);
}

- (void)resignFirstResponder {
    [_textView resignFirstResponder];
}

#pragma mark - lazy

- (HXPhotoManager *)photoManage {
    if (!_photoManage) {
        _photoManage = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto];
        _photoManage.configuration.type = HXConfigurationTypeWXMoment;
        _photoManage.configuration.openCamera = YES;
        _photoManage.configuration.photoMaxNum = 9;
        _photoManage.configuration.videoMaxNum = 0;
        _photoManage.configuration.maxNum = 9;
        _photoManage.configuration.lookLivePhoto = YES;
        _photoManage.configuration.selectTogether = NO;
        _photoManage.configuration.deleteTemporaryPhoto = YES;
        _photoManage.configuration.creationDateSort = YES;
    }
    return _photoManage;
}

-(HXPhotoManager *)videoManage {
    if (!_videoManage) {
        _videoManage = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypeVideo];
        _videoManage.configuration.type = HXConfigurationTypeWXMoment;
        _videoManage.configuration.openCamera = YES;
        _videoManage.configuration.photoMaxNum = 0;
        _videoManage.configuration.videoMaxNum = 9;
        _videoManage.configuration.maxNum = 9;
        _videoManage.configuration.lookLivePhoto = YES;
        _videoManage.configuration.selectTogether = NO;
        _videoManage.configuration.deleteTemporaryPhoto = YES;
        _videoManage.configuration.creationDateSort = YES;
        
        _videoManage.configuration.videoMaximumSelectDuration = 60 * 10;
    }
    return _videoManage;
}

@end
